use std::io;
use std::process;
use std::env; 


fn input_number(message: &str) -> f32 {

    println!("{}", message);
    let mut string =  String::new();
    io::stdin()
        .read_line(&mut string)
        .expect("Input error");
    let number: f32 = string.trim().parse::<f32>().unwrap_or_else(|err| {
       eprintln!("Number of participants must be interger: {}", err);
       process::exit(1);
    });

    number       

}

#[derive(Debug)]
#[derive(PartialEq)]
struct Payment {
    car_owner: f32,
    passenger: f32,
}

fn main() {
   
   let participants = input_number("Enter number of participants: ");
   let goods_cost = input_number("Enter cost of goods: ");
   let oil_cost = input_number("Enter cost of oil: ");

   let payment = calculate_payments(participants, goods_cost, oil_cost);
   
   // import CAR_OWNER_NAME from evnironment (optional argument)
   let car_owner_name = match env::var("CAR_OWNER_NAME")  {
        Ok(name) => name.to_owned(),
        Err(err) => String::from("Car owner"),
   };

   println!("{} have to pay: {}",car_owner_name, payment.car_owner);
   println!("Every passenger have to pay: {}", payment.passenger);
    


}




fn calculate_payments(participants: f32, goods_cost: f32, oil_cost: f32) -> Payment {
    
    // math model (equation)
    //
    // (participants - 1) * payment_for_passenger + payment_for_car_owner = goods 
    //
    // payment_for_car_owner = payment_for_passenger - oil * (n-1 / n)
    // participants * payment_for_passenger - oil * (n-1 / n) = goods 
    // participants * payment_for_passenger = goods +  oil * (n-1 / n)
    // payment_for_passenger = (goods +  oil * (n - 1 / n) ) / n
    
    
    Payment {
        car_owner: (goods_cost +  oil_cost * ((participants - 1.0)/ participants) )
            / participants - oil_cost * ((participants - 1.0) / participants),

        passenger: (goods_cost +  oil_cost * ((participants - 1.0)/ participants) )
            / participants,
    }

} 


#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn two_participants() {
       let participants = 2.0;
       let goods_cost = 500.0;
       let oil_cost = 400.0;

       let expected_payment = Payment {
           car_owner: 150.0,
           passenger: 350.0,
        };
        
       assert_eq!(calculate_payments(participants, goods_cost, oil_cost), expected_payment);



    }
}

